package com.crazyimp.utilities;

import java.util.Stack;

public class DataWorker {
	
	private Stack<Request> stack;
	private volatile boolean stop;
	private Thread thread;
	private volatile boolean started = false;
	private Runnable download = new Runnable(){
		@Override
		public void run() {
			while(!stop && !stack.isEmpty()){
				startModify();
				final Request request = stack.pop();
				if (request != null){					
					if (!stop){
						if (request.listener != null)
							request.listener.onData(request.requestCode, request.data);
					}
					else
						stack.add(request);
				}
				stopModify();
			}
		}
	};
	private volatile boolean modify = true;
	
	public DataWorker(){
		stack = new Stack<Request>();		
		stop = false;
		thread = new Thread(download);
		thread.setDaemon(true);
	}
		
	private class Request {
		public int requestCode;
		public Object data;
		public IDataListener listener;
	}
	
	/**
	 * 
	 * @param requestCode
	 * @param data
	 * @param listener
	 */	
	public void addRequest(final int requestCode, final Object data, final IDataListener listener){
		final Request request = new Request();
		request.data = data;
		request.requestCode = requestCode;
		request.listener = listener;
		stack.add(request);
		if (!thread.isAlive()){
			startThread();
		}
	}

	public void stopDataWorker(){
		stop = true;
	}
	
	public synchronized void startDataWorker(){
		if (!stack.isEmpty() && !thread.isAlive()){
			startThread();
		}
	}
	
	private void startThread(){
		if (started){
			thread = new Thread(download);
			thread.setDaemon(true);
			thread.start();
		} else {
			started = true;
			thread.start();
		}
	}
	
	public synchronized void startModify(){
		while(!modify){}
		modify = false;
	}
	
	public void stopModify(){
		modify = true;
	}
	
}
